package com.company.ems.controller;

import com.company.ems.dao.EmployeeDAO;
import com.company.ems.dao.EmployeeDAOImpl;
import com.company.ems.model.Employee;
import com.company.ems.model.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/employee/*")
public class EmployeeServlet extends HttpServlet {
    private EmployeeDAO employeeDAO = new EmployeeDAOImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        String pathInfo = request.getPathInfo();
        
        if (pathInfo == null || pathInfo.equals("/")) {
            listEmployees(request, response);
        } else if (pathInfo.equals("/add")) {
            request.getRequestDispatcher("/employee/add.jsp").forward(request, response);
        } else if (pathInfo.equals("/edit")) {
            showEditForm(request, response);
        } else if (pathInfo.equals("/view")) {
            viewEmployee(request, response);
        } else if (pathInfo.equals("/delete")) {
            deleteEmployee(request, response);
        } else if (pathInfo.equals("/search")) {
            searchEmployees(request, response);
        } else {
            // 处理未知路径，重定向到员工列表
            response.sendRedirect(request.getContextPath() + "/employee/");
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        String pathInfo = request.getPathInfo();
        
        if (pathInfo != null) {
            if (pathInfo.equals("/add")) {
                addEmployee(request, response);
            } else if (pathInfo.equals("/update")) {
                updateEmployee(request, response);
            } else {
                // 处理其他POST请求，默认跳转到员工列表
                response.sendRedirect(request.getContextPath() + "/employee/");
            }
        } else {
            // 如果pathInfo为null，默认跳转到员工列表
            response.sendRedirect(request.getContextPath() + "/employee/");
        }
    }
    
    private void listEmployees(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        try {
            List<Employee> employees = employeeDAO.findAll();
            request.setAttribute("employees", employees);
            // 清除可能存在的加载状态属性
            request.removeAttribute("loading");
            request.getRequestDispatcher("/employee/list.jsp").forward(request, response);
        } catch (Exception e) {
            // 处理异常，防止请求被卡住
            request.setAttribute("error", "获取员工列表失败: " + e.getMessage());
            request.getRequestDispatcher("/employee/list.jsp").forward(request, response);
        }
    }
    
    private void showEditForm(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        try {
            int id = Integer.parseInt(request.getParameter("id"));
            Employee employee = employeeDAO.findById(id);
            if (employee != null) {
                request.setAttribute("employee", employee);
                request.getRequestDispatcher("/employee/edit.jsp").forward(request, response);
            } else {
                // 如果员工不存在，重定向到员工列表
                response.sendRedirect(request.getContextPath() + "/employee/");
            }
        } catch (NumberFormatException e) {
            // 如果ID不是有效数字，重定向到员工列表
            response.sendRedirect(request.getContextPath() + "/employee/");
        }
    }
    
    private void viewEmployee(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        try {
            int id = Integer.parseInt(request.getParameter("id"));
            Employee employee = employeeDAO.findById(id);
            if (employee != null) {
                request.setAttribute("employee", employee);
                request.getRequestDispatcher("/employee/view.jsp").forward(request, response);
            } else {
                // 如果员工不存在，重定向到员工列表
                response.sendRedirect(request.getContextPath() + "/employee/");
            }
        } catch (NumberFormatException e) {
            // 如果ID不是有效数字，重定向到员工列表
            response.sendRedirect(request.getContextPath() + "/employee/");
        }
    }
    
    private void addEmployee(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        try {
            Employee employee = new Employee();
            employee.setName(request.getParameter("name"));
            employee.setDepartment(request.getParameter("department"));
            employee.setPosition(request.getParameter("position"));
            employee.setSalary(java.math.BigDecimal.valueOf(Double.parseDouble(request.getParameter("salary"))));
            employee.setEmail(request.getParameter("email"));
            employee.setPhone(request.getParameter("phone"));
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date hireDate = sdf.parse(request.getParameter("hireDate"));
            employee.setHireDate(hireDate);
            
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("user");
            employee.setCreatedBy(user.getId());
            
            if (employeeDAO.add(employee)) {
                // 使用完整的上下文路径进行重定向
                String contextPath = request.getContextPath();
                response.sendRedirect(contextPath + "/employee/");
            } else {
                request.setAttribute("error", "添加员工失败");
                request.getRequestDispatcher("/employee/add.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "添加员工失败：" + e.getMessage());
            request.getRequestDispatcher("/employee/add.jsp").forward(request, response);
        }
    }
    
    private void updateEmployee(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        try {
            Employee employee = new Employee();
            employee.setId(Integer.parseInt(request.getParameter("id")));
            employee.setName(request.getParameter("name"));
            employee.setDepartment(request.getParameter("department"));
            employee.setPosition(request.getParameter("position"));
            employee.setSalary(java.math.BigDecimal.valueOf(Double.parseDouble(request.getParameter("salary"))));
            employee.setEmail(request.getParameter("email"));
            employee.setPhone(request.getParameter("phone"));
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date hireDate = sdf.parse(request.getParameter("hireDate"));
            employee.setHireDate(hireDate);
            
            if (employeeDAO.update(employee)) {
                // 使用完整的上下文路径进行重定向
                String contextPath = request.getContextPath();
                response.sendRedirect(contextPath + "/employee/");
            } else {
                request.setAttribute("error", "更新员工失败");
                request.setAttribute("employee", employee);
                request.getRequestDispatcher("/employee/edit.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "更新员工失败：" + e.getMessage());
            try {
                int id = Integer.parseInt(request.getParameter("id"));
                Employee employee = employeeDAO.findById(id);
                request.setAttribute("employee", employee);
            } catch (Exception ex) {
                request.setAttribute("error", "获取员工信息失败: " + ex.getMessage());
            }
            request.getRequestDispatcher("/employee/edit.jsp").forward(request, response);
        }
    }
    
    private void deleteEmployee(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        try {
            int id = Integer.parseInt(request.getParameter("id"));
            employeeDAO.delete(id);
        } catch (NumberFormatException e) {
            // 如果ID不是有效数字，忽略错误
            e.printStackTrace();
            request.setAttribute("error", "删除员工失败: " + e.getMessage());
        }
        // 使用完整的上下文路径进行重定向
        String contextPath = request.getContextPath();
        response.sendRedirect(contextPath + "/employee/");
    }
    
    private void searchEmployees(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String name = request.getParameter("name");
        String department = request.getParameter("department");
        String position = request.getParameter("position");
        
        List<Employee> employees = employeeDAO.findByCondition(name, department, position);
        request.setAttribute("employees", employees);
        request.setAttribute("name", name);
        request.setAttribute("department", department);
        request.setAttribute("position", position);
        
        request.getRequestDispatcher("/employee/list.jsp").forward(request, response);
    }
}